//
//  HNSH_ChatListViewController.m
//  HNSH_SingleProject
//
//  Created by 李宇廷 on 2023/2/16.
//

#import "HNSH_ChatListViewController.h"

//view
#import "HNSH_ChatListCell.h"

//vc
#import "HNSH_ChatSingleViewController.h"       //单聊
#import "HNSH_ChatGroupViewController.h"        //群聊

@interface HNSH_ChatListViewController ()

@property (nonatomic, strong) NSMutableArray *specialAry;

@end

static NSString *HNSH_ChatListCellID = @"HNSH_ChatListCellID";

@implementation HNSH_ChatListViewController

- (void)setParameter:(NSString *)parameter {
    _parameter = parameter;
    [self loadUploadData];
}

- (void)loadUploadData {
    [self refreshConversationTableViewIfNeeded];
    //刷新特殊群列表
    [self loadRongCloudGroupSpecialList];
}

//MARK: Cycle Methods
- (void)viewDidLoad{
    [super viewDidLoad];
    
    self.navigationController.navigationBar.hidden = YES;

    [self addAllViews];
    
    [self setDefault];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadUploadData) name:@"KUpLoadChatListData" object:nil];
    [self.conversationListTableView registerClass:[HNSH_ChatListCell class] forCellReuseIdentifier:HNSH_ChatListCellID];
    
    //收藏小红点
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(collectClear) name:@"kCollectMsgCountChange" object:nil];
}

- (void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];
    
    self.conversationListTableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - kNavBarAndStatusBarHeight - 40 );
//    [self.conversationListTableView registerClass:[DLNewMessagesViewHeader class] forCellReuseIdentifier:DLNewMessagesViewHeaderID];
}

#pragma mark - Custom Methods
- (void)addAllViews{
    self.emptyConversationView = [UIView new];
    self.emptyConversationView.hidden = YES;
    self.isShowNetworkIndicatorView = NO;
    self.conversationListTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//    [self.view addSubview:self.navView];
    self.cellBackgroundColor = [UIColor appWhiteLabelColor];
    [self configHeader];
}

- (void)collectClear {
//    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
//    DLNewMessagesViewHeader *cell = [self.conversationListTableView cellForRowAtIndexPath:indexPath];
//    cell.countLabel.hidden = NO;
}

- (void)configHeader {

}

#pragma mark - Myself Methods
- (void)setDefault{
    //设置需要显示哪些类型的会话
    [self setDisplayConversationTypes:@[@(ConversationType_PRIVATE), @(ConversationType_GROUP)]];
    [RCIM sharedRCIM].receiveMessageDelegate = self;
    [RCIM sharedRCIM].connectionStatusDelegate = self;
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didReceiveMessageNotification:)name:RCKitDispatchMessageNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didReceiveMessageNotification:)name:RCKitDispatchMessageReceiptResponseNotification object:nil];
    
}

//MARK: back
- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)search{
    
}

/*!
 接收消息的回调方法
 *
 */
//-(void)onRCIMReceiveMessage:(RCMessage *)message left:(int)left
//{
//    NSLog(@" onRCIMReceiveMessage %@",message.content);
//    RCMessageContent * content = (RCMessageContent *)message.content;
//    RCUserInfo * user = content.senderUserInfo;
//    if (user) {
//        [[RCIM sharedRCIM] refreshUserInfoCache:user withUserId:user.userId];
//    }
//    [[RCDRCIMDataSource sharedInstance] refreshBadgeValue];
//    dispatch_async(dispatch_get_main_queue(), ^{
//        [self.conversationListTableView reloadData];
//    });
//}

#pragma mark - 收到消息监听
-(void)didReceiveMessageNotification:(NSNotification *)notification{
    __weak typeof(&*self) blockSelf_ = self;
    //处理好友请求
    RCMessage *message = notification.object;
    
    if ([message.content isMemberOfClass:[RCMessageContent class]]) {
        if (message.conversationType == ConversationType_PRIVATE) {
            NSLog(@"好友消息要发系统消息！！！");
            @throw  [[NSException alloc] initWithName:@"error" reason:@"好友消息要发系统消息！！！" userInfo:nil];
        }
        RCConversationModel *customModel = [RCConversationModel new];
        //自定义cell的type
        customModel.conversationModelType = RC_CONVERSATION_MODEL_TYPE_CUSTOMIZATION;
        customModel.senderUserId = message.senderUserId;
        customModel.lastestMessage = message.content;
        dispatch_async(dispatch_get_main_queue(), ^{
            //调用父类刷新未读消息数
//            [blockSelf_ refreshConversationTableViewWithConversationModel:customModel];
            [super didReceiveMessageNotification:notification];
//            [blockSelf_ resetConversationListBackgroundViewIfNeeded];
            [self notifyUpdateUnreadMessageCount];
            
            //当消息为RCContactNotificationMessage时，没有调用super，如果是最后一条消息，可能需要刷新一下整个列表。
            //原因请查看super didReceiveMessageNotification的注释。
            
        });
        
    }else if (message.conversationType == ConversationType_PRIVATE){
        //获取接受到会话
        RCConversation *receivedConversation = [[RCIMClient sharedRCIMClient] getConversation:message.conversationType targetId:message.targetId];
        
        //转换新会话为新会话模型
        RCConversationModel *customModel = [[RCConversationModel alloc] initWithConversation:receivedConversation extend:nil];
        dispatch_async(dispatch_get_main_queue(), ^{
            //调用父类刷新未读消息数
//            [blockSelf_ refreshConversationTableViewWithConversationModel:customModel];
            //[super didReceiveMessageNotification:notification];
//            [blockSelf_ resetConversationListBackgroundViewIfNeeded];
            [self notifyUpdateUnreadMessageCount];
            
            //当消息为RCContactNotificationMessage时，没有调用super，如果是最后一条消息，可能需要刷新一下整个列表。
            //原因请查看super didReceiveMessageNotification的注释。
            NSNumber *left = [notification.userInfo objectForKey:@"left"];
            if (0 == left.integerValue) {
                [super refreshConversationTableViewIfNeeded];
            }
        });
    } else if (message.conversationType == ConversationType_SYSTEM) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"kRefreshUnreadCount" object:nil];
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            //            调用父类刷新未读消息数
            [super didReceiveMessageNotification:notification];
            [self notifyUpdateUnreadMessageCount];
            
            //        super会调用notifyUpdateUnreadMessageCount
        });
    }
    [self refreshConversationTableViewIfNeeded];
}

- (void)loadUserAndGroupInfoWithUserArray:(NSArray *)userArray groupArray:(NSArray *)groupArray{
    if (userArray.count <= 0 && groupArray.count <= 0) {
        return;
    }
    NSArray * userIdsArray = [self getIdsArrayWithArray:userArray];
    NSArray * groupIdsArray = [self getIdsArrayWithArray:groupArray];
    [HNSH_ChatNetServer requestRongCloudGroupInfoListWithGroupIds:groupIdsArray ids:userIdsArray success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            BOOL isChange = NO;
            NSArray * users = responseObject.resultset[@"users"];
            NSMutableArray *userAry = [NSMutableArray arrayWithArray:userIdsArray];
            for (NSDictionary * user in users) {
                NSString *userId = [NSString stringWithFormat:@"%@",user[@"id"]];
                BOOL isHave = NO;
                for (NSString *userIdStr in userAry) {
                    if ([userIdStr isEqualToString:userId]) {
                        [userAry removeObject:userIdStr];
                        isHave = YES;
                        break;
                    }
                }
                if (!isHave) {
                    return;
                }
                RCUserInfo * userInfo = [[RCUserInfo alloc] init];
                userInfo.userId = userId;
                NSString * displayName = user[@"display_name"];
                userInfo.name = displayName.length ? displayName : user[@"name"];
                userInfo.portraitUri = user[@"portrait"];
                userInfo.extra = user[@"extra"];
                [[RCIM sharedRCIM] refreshUserInfoCache:userInfo withUserId:userId];
            }
            for (NSString *userId in userAry) {
                //删除消息
                [[RCIMClient sharedRCIMClient] clearMessages:ConversationType_PRIVATE targetId:userId];
                //删除本地会话
                [[RCIMClient sharedRCIMClient] removeConversation:ConversationType_PRIVATE targetId:userId];
                isChange = YES;
            }
            NSArray * groups = responseObject.resultset[@"groups"];
            NSMutableArray *groupAry = [NSMutableArray arrayWithArray:groupIdsArray];
            for (NSDictionary * group in groups) {
                NSString *groupId = [NSString stringWithFormat:@"%@",group[@"encode_id"]];
                BOOL isHave = NO;
                for (NSString *groupIdStr in groupAry) {
                    if ([groupIdStr isEqualToString:groupId]) {
                        [groupAry removeObject:groupIdStr];
                        isHave = YES;
                        break;
                    }
                }
                if (!isHave) {
                    return;
                }
                RCGroup * groupInfo = [[RCGroup alloc] init];
                groupInfo.groupId = groupId;
                NSString * displayName = group[@"display_name"];
                groupInfo.groupName = displayName.length ? displayName : group[@"name"];
                groupInfo.portraitUri = group[@"portrait_url"];
                [[RCIM sharedRCIM] refreshGroupInfoCache:groupInfo withGroupId:groupId];
            }
            for (NSString *groupId in groupAry) {
                //删除消息
                [[RCIMClient sharedRCIMClient] clearMessages:ConversationType_GROUP targetId:groupId];
                //删除本地会话
                [[RCIMClient sharedRCIMClient] removeConversation:ConversationType_GROUP targetId:groupId];
                isChange = YES;
            }
            if (isChange) {
                [self refreshConversationTableViewIfNeeded];
            }
            int count = [[RCIMClient sharedRCIMClient] getUnreadCount:@[@1,@2,@3] containBlocked:NO];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"KUnreadCountNoti" object:self userInfo:@{@"count":@(count)}];
            [self.conversationListTableView reloadData];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

- (void)loadRongCloudGroupSpecialList {
//    [CFBNetworkHelper getDataWithPathUrl:URL_RongCloud_Group_Special_List params:@{} from:YES needToken:YES successBlock:^(BOOL result, NSString * _Nonnull message, NSDictionary * _Nonnull dic) {
//        if (result) {
//            [self.specialAry removeAllObjects];
////            [self.specialAry addObject:[NYGroupSpecialModel new]];
//            [self.specialAry addObjectsFromArray:[NSArray yy_modelArrayWithClass:[NYGroupSpecialModel class] json:dic[@"data"]]];
//            UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 76 * self.specialAry.count)];
//            for (int i = 0; i < self.specialAry.count; i ++) {
//                DLNewMessagesViewHeader *cell = [[DLNewMessagesViewHeader alloc]initWithFrame:CGRectMake(0, 76*i, kScreenWidth, 76)];
//                cell.tag = i;
////                if (i > 0) {
//                    cell.imgView.image = [UIImage imageNamed:@"chat_icon_myqun"];
//                    cell.infoModel = self.specialAry[i];
//                    cell.statusButton.hidden = NO;
////                } else {
////                    cell.imgView.image = [UIImage imageNamed:@"chat_list_shouchang"];
////                    cell.nameLabel.text = @"收藏夹";
////                    cell.conLabel.text = @"";
////                    cell.statusButton.hidden = YES;
////                }
//                __weak __typeof(DLNewMessagesViewHeader *)weakCell = cell;
//                __weak __typeof(&*self)weakSelf = self;
//                cell.clickBlock = ^(NSInteger index) {
////                    if (index == 0) {
////                        weakCell.countLabel.hidden = YES;
////                        NYChatCollectionViewController *vc = [[NYChatCollectionViewController alloc]init];
////                        [[CFBHelper getTopViewController].navigationController pushViewController:vc animated:YES];
////                    } else {
//                        NYGroupSpecialModel * model = weakSelf.specialAry[i];
//                        [weakSelf loadRongCloudGroupSpecialApply:model.encode_id];
////                    }
//                };
//                [headerView addSubview:cell];
//            }
//            self.conversationListTableView.tableHeaderView = headerView;
//        }
//    } failBlock:^(NSError * _Nonnull error) {
//
//    }];
}

- (void)loadRongCloudGroupSpecialApply:(NSString *)group_id {
    [HNSH_ChatNetServer requestRongCloudGroupApplyWithGroupId:group_id success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            [self.view makeToast:@"您的申请已提交，等待管理员审核"];
            [self loadRongCloudGroupSpecialList];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

- (NSArray *)getIdsArrayWithArray:(NSArray *)array{
    NSMutableArray * userArray = [NSMutableArray new];
    for (RCConversationModel * obj in array) {
        [userArray addObject:obj.targetId];
    }
    return userArray.copy;
}

/** 把所有消息转换成自定义 方便处理 */
- (NSMutableArray<RCConversationModel *> *)willReloadTableData:(NSMutableArray<RCConversationModel *> *)dataSource{
    NSMutableArray * userArray = [NSMutableArray new];
    NSMutableArray * groupArray = [NSMutableArray new];
    for (RCConversationModel * obj in dataSource) {
        obj.conversationModelType = RC_CONVERSATION_MODEL_TYPE_CUSTOMIZATION;
        //
        if (obj.conversationType == ConversationType_PRIVATE) {
            [userArray addObject:obj];
        }
        if (obj.conversationType == ConversationType_GROUP) {
            [groupArray addObject:obj];
        }
    }
    [self loadUserAndGroupInfoWithUserArray:userArray groupArray:groupArray];
    return dataSource;
}

- (RCConversationBaseCell *)rcConversationListTableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HNSH_ChatListCell *cell = [tableView dequeueReusableCellWithIdentifier:HNSH_ChatListCellID];
    cell.model = self.conversationListDataSource[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.conversationListDataSource.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01f;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01f;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [UIView new];
}
/** 自定义设置cell的高度 */
- (CGFloat)rcConversationListTableView:(UITableView *)tableView
               heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 68;
}

- (void)onSelectedTableRow:(RCConversationModelType)conversationModelType
         conversationModel:(RCConversationModel *)model
               atIndexPath:(NSIndexPath *)indexPath{
    if (model.conversationType == ConversationType_GROUP) {
        HNSH_ChatGroupViewController * vc = [HNSH_ChatGroupViewController new];
        vc.conversationType = ConversationType_GROUP;
        vc.targetId = model.targetId;
        [[UIViewControllerHelper findCurrentShowingViewController].navigationController pushViewController:vc animated:YES];
    } else {
        RCUserInfo * userInfo = [[RCIM sharedRCIM] getUserInfoCache:model.targetId];
        HNSH_ChatSingleViewController * vc = [HNSH_ChatSingleViewController new];
        vc.conversationType = ConversationType_PRIVATE;
        vc.targetId = model.targetId;
        vc.title = userInfo.name;
        [[UIViewControllerHelper findCurrentShowingViewController].navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - 删除的相关代理方法
- (nullable UISwipeActionsConfiguration *)tableView:(UITableView *)tableView leadingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath API_AVAILABLE(ios(11.0)) API_UNAVAILABLE(tvos){
    [tableView setEditing:NO animated:YES];
    UISwipeActionsConfiguration *actions = [[UISwipeActionsConfiguration alloc] init];
    return actions;
}

/** ios(11.0)开始的方法重写这个方法，删除iOS 11左滑到头直接删除的功能 */
- (nullable UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath API_AVAILABLE(ios(11.0)) API_UNAVAILABLE(tvos){
    RCConversationModel * model = self.conversationListDataSource[indexPath.row];
    UIContextualAction * deleteAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:@"删除" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
        //这句很重要，退出编辑模式，隐藏左滑菜单
        [tableView setEditing:NO animated:YES];
        //删除本地会话，不删除消息
        [[RCIMClient sharedRCIMClient] removeConversation:model.conversationType targetId:model.targetId];
        //删除消息
        [[RCIMClient sharedRCIMClient] clearMessages:model.conversationType targetId:model.targetId];
        [self.conversationListDataSource removeObjectAtIndex:indexPath.row];
        [self.conversationListTableView reloadData];
        completionHandler(true);
    }];
    UISwipeActionsConfiguration *actions = [UISwipeActionsConfiguration configurationWithActions:@[deleteAction]];
    actions.performsFirstActionWithFullSwipe = NO;
    return actions;
}

//ios(8.0, 13.0)
- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    RCConversationModel *model = self.conversationListDataSource[indexPath.row];
    UITableViewRowAction *action1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        //可以从数据库删除数据
        [[RCIMClient sharedRCIMClient] removeConversation:model.conversationType targetId:model.targetId];
        [[RCIMClient sharedRCIMClient] clearMessages:model.conversationType targetId:model.targetId];
        [self.conversationListDataSource removeObjectAtIndex:indexPath.row];
        [self.conversationListTableView reloadData];
    }];
    return @[action1];
}
- (void)onRCIMConnectionStatusChanged:(RCConnectionStatus)status {
    NSLog(@"RCConnectionStatus = %ld",(long)status);
    if (status == ConnectionStatus_KICKED_OFFLINE_BY_OTHER_CLIENT) {
        
    }
}


- (NSMutableArray *)specialAry {
    if (!_specialAry) {
        _specialAry = [NSMutableArray arrayWithCapacity:0];
    }
    return _specialAry;
}


@end
